<template>
  <div class="student-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
          <el-button 
            v-if="!isEditing" 
            type="primary" 
            @click="startEdit"
            :disabled="showInvalidUserWarning"
          >
            编辑资料
          </el-button>
          <div v-else>
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="saveProfile" :loading="saving">保存</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-state">
        <el-skeleton animated>
          <template #template>
            <el-skeleton-item variant="h3" style="width: 50%" />
            <div style="margin-top: 20px">
              <el-skeleton-item variant="p" style="width: 100%" />
              <el-skeleton-item variant="p" style="width: 100%; margin-top: 10px" />
              <el-skeleton-item variant="p" style="width: 100%; margin-top: 10px" />
            </div>
          </template>
        </el-skeleton>
      </div>
      
      <div v-else>
        <el-alert 
          v-if="showInvalidUserWarning"
          :title="`用户信息不完整，请重新登录 (当前ID: ${props.currentUserId || '无'})`" 
          type="warning" 
          show-icon 
          style="margin-bottom: 20px"
        />
        
        <el-form 
          ref="formRef" 
          :model="profileForm" 
          :rules="rules" 
          label-width="120px"
          :disabled="!isEditing || showInvalidUserWarning"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realName">
                <el-input v-model="profileForm.realName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学号" prop="studentNo">
                <el-input v-model="profileForm.studentNo" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学院" prop="college">
                <el-input v-model="profileForm.college" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" prop="major">
                <el-input v-model="profileForm.major" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="年级" prop="grade">
                <el-select v-model="profileForm.grade" placeholder="请选择年级" style="width: 100%">
                  <el-option label="大一" value="大一" />
                  <el-option label="大二" value="大二" />
                  <el-option label="大三" value="大三" />
                  <el-option label="大四" value="大四" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班级" prop="className">
                <el-input v-model="profileForm.className" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="技能标签" prop="skills">
            <el-select 
              v-model="profileForm.skills" 
              multiple 
              filterable 
              allow-create 
              default-first-option
              placeholder="请输入技能标签，可创建新标签"
              style="width: 100%"
            >
              <el-option label="Java" value="Java" />
              <el-option label="Python" value="Python" />
              <el-option label="C++" value="C++" />
              <el-option label="JavaScript" value="JavaScript" />
              <el-option label="HTML/CSS" value="HTML/CSS" />
              <el-option label="Vue.js" value="Vue.js" />
              <el-option label="React" value="React" />
              <el-option label="Node.js" value="Node.js" />
              <el-option label="数据库" value="数据库" />
              <el-option label="UI设计" value="UI设计" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="兴趣爱好" prop="interests">
            <el-select 
              v-model="profileForm.interests" 
              multiple 
              filterable 
              allow-create 
              default-first-option
              placeholder="请输入兴趣爱好，可创建新标签"
              style="width: 100%"
            >
              <el-option label="音乐" value="音乐" />
              <el-option label="绘画" value="绘画" />
              <el-option label="摄影" value="摄影" />
              <el-option label="运动" value="运动" />
              <el-option label="阅读" value="阅读" />
              <el-option label="编程" value="编程" />
              <el-option label="游戏" value="游戏" />
              <el-option label="旅行" value="旅行" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="自我介绍" prop="selfIntroduction">
            <el-input 
              v-model="profileForm.selfIntroduction" 
              type="textarea" 
              :rows="4" 
              placeholder="请简单介绍一下自己，包括特长、经历等"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <el-card class="stats-card">
      <template #header>
        <span>个人统计</span>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-value">{{ stats.applicationCount || 0 }}</div>
            <div class="stat-label">申请数量</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-value">{{ stats.appointmentCount || 0 }}</div>
            <div class="stat-label">面试预约</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-value">{{ stats.recommendationCount || 0 }}</div>
            <div class="stat-label">推荐数量</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import studentProfileApi from '@/api/campus/student/studentProfile'
import useUserStore from '@/store/modules/user'

// 使用解构赋值从默认导出中获取函数
const { 
  getCurrentStudentProfile, 
  updateStudentProfile: apiUpdateStudentProfile,
  getStudentPortalData
} = studentProfileApi

// Props
const props = defineProps({
  currentUserId: {
    type: [String, Number],
    required: false,
    default: ''
  }
})

// 从多个可能的位置获取用户ID的辅助函数
const getUserIdFromStorage = () => {
  // 打印所有localStorage键值对，调试用
  console.log('===== localStorage 内容分析 =====');
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    try {
      const value = localStorage.getItem(key);
      console.log(`localStorage[${key}]:`, value);
      
      // 特别检查用户相关的关键字段
      if (key.toLowerCase().includes('user') || 
          key.toLowerCase().includes('token') || 
          key.toLowerCase().includes('auth')) {
        console.log(`🚨 可能包含用户信息的字段: ${key}`);
        // 尝试解析为对象
        try {
          const parsed = JSON.parse(value);
          console.log(`解析后内容:`, parsed);
        } catch (e) {
          console.log(`不是JSON格式`);
        }
      }
    } catch (e) {
      console.log(`读取 ${key} 时出错:`, e);
    }
  }
  console.log('==================================');

  // 尝试从所有可能的位置获取用户ID
  let userId = '';
  
  // 1. 尝试从常见的用户ID字段获取
  const userIdKeys = ['userId', 'id', 'user_id', 'username', 'loginName', 'account'];
  for (const key of userIdKeys) {
    const value = localStorage.getItem(key);
    if (value && value.trim()) {
      userId = value;
      console.log(`1. 从 ${key} 获取到用户ID:`, userId);
      break;
    }
  }
  
  // 2. 尝试从userInfo对象中获取各种可能的用户ID字段
  if (!userId) {
    try {
      const userInfoStr = localStorage.getItem('userInfo') || localStorage.getItem('userinfo');
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        console.log('发现userInfo对象:', userInfo);
        
        // 尝试所有可能的用户ID字段名
        const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'studentId'];
        for (const field of possibleIdFields) {
          if (userInfo[field] && String(userInfo[field]).trim()) {
            userId = String(userInfo[field]);
            console.log(`2. 从userInfo.${field}获取到用户ID:`, userId);
            break;
          }
        }
      }
    } catch (e) {
      console.warn('解析userInfo失败:', e);
    }
  }
  
  // 3. 尝试从token或其他认证信息中获取
  if (!userId) {
    try {
      const tokenKeys = ['token', 'Authorization', 'auth_token', 'access_token'];
      let token = '';
      
      for (const key of tokenKeys) {
        token = localStorage.getItem(key);
        if (token) break;
      }
      
      if (token) {
        console.log('发现token:', token);
        // 简单尝试解码token前半部分
        try {
          const tokenParts = token.split('.');
          if (tokenParts.length >= 2) {
            const decoded = JSON.parse(atob(tokenParts[1].replace(/-/g, '+').replace(/_/g, '/')));
            console.log('token解码内容:', decoded);
            
            // 尝试所有可能的用户ID字段名
            const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'sub', 'name'];
            for (const field of possibleIdFields) {
              if (decoded[field] && String(decoded[field]).trim()) {
                userId = String(decoded[field]);
                console.log(`3. 从token.${field}获取到用户ID:`, userId);
                break;
              }
            }
          }
        } catch (e) {
          console.warn('解码token失败:', e);
        }
      }
    } catch (e) {
      console.warn('从token获取用户ID失败:', e);
    }
  }
  
  return userId;
};

// 计算属性：获取有效的用户ID（同时检查props、store和localStorage的多个位置）
const getValidUserId = computed(() => {
  // 1. 从store获取用户ID（最高优先级）
  try {
    const userStore = useUserStore();
    if (userStore && userStore.id) {
      console.log('从store获取到用户ID:', userStore.id);
      return String(userStore.id).trim();
    }
  } catch (error) {
    console.warn('获取store用户信息失败:', error);
  }
  
  // 2. 从props获取userId
  const userIdFromProps = String(props.currentUserId || '').trim();
  console.log('props中的用户ID:', userIdFromProps);
  
  // 3. 从localStorage获取userId
  const userIdFromStorage = getUserIdFromStorage();
  
  // 使用第一个有效的用户ID
  const validUserId = userIdFromProps || userIdFromStorage;
  
  console.log('最终有效用户ID:', validUserId);
  return validUserId;
});

// 判断用户ID是否无效
const isUserIdInvalid = computed(() => {
  const validUserId = getValidUserId.value;
  return !validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '';
});

// 判断是否显示无效用户警告
const showInvalidUserWarning = computed(() => {
  return isUserIdInvalid.value;
});

// Data
const loading = ref(false)
const profile = ref({})
const isEditing = ref(false)
const formRef = ref(null)
const saving = ref(false)
const stats = ref({
  applicationCount: 0,
  appointmentCount: 0,
  recommendationCount: 0
})

// 表单数据和验证规则
const profileForm = ref({
  realName: '',
  studentNo: '',
  college: '',
  major: '',
  grade: '',
  className: '',
  skills: [],
  interests: [],
  selfIntroduction: ''
})

const rules = ref({
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  studentNo: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  college: [
    { required: true, message: '请输入学院', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ]
})

// 工具函数：安全地解析JSON数组
const parseJsonArray = (jsonString) => {
  if (!jsonString || typeof jsonString !== 'string') {
    return []
  }
  
  try {
    // 尝试直接解析JSON字符串
    const parsed = JSON.parse(jsonString)
    // 确保返回的是数组
    return Array.isArray(parsed) ? parsed : []
  } catch (error) {
    console.warn('解析JSON数组失败，尝试简单分割:', jsonString, error)
    // 备用方案：如果不是有效的JSON，尝试按逗号分割
    return jsonString.split(',').map(item => item.trim()).filter(item => item)
  }
}

// 先定义resetForm函数，避免在其他函数中引用未初始化的问题
const resetForm = () => {
  profileForm.value = {
    realName: '',
    studentNo: '',
    college: '',
    major: '',
    grade: '',
    className: '',
    skills: [],
    interests: [],
    selfIntroduction: ''
  }
}

// Methods - 修改loadProfile函数，使用改进的用户ID获取逻辑
const loadProfile = async () => {
  const validUserId = getValidUserId.value;
  
  console.log('开始加载个人资料，用户ID:', validUserId);
  
  if (!validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '') {
    console.warn('用户ID无效，无法加载个人资料');
    ElMessage.warning('请先登录后再操作');
    resetForm();
    return;
  }
  
  loading.value = true;
  try {
    // 使用有效的用户ID获取资料
    const response = await getCurrentStudentProfile(validUserId);
    console.log('获取当前用户资料响应:', response);
    
    if (response.code === 200) {
      profile.value = response.data || {}
      console.log('获取到的个人资料:', profile.value)
      
      // 更新表单数据
      profileForm.value = {
        realName: profile.value.realName || '',
        studentNo: profile.value.studentNo || '',
        college: profile.value.college || '',
        major: profile.value.major || '',
        grade: profile.value.grade || '',
        className: profile.value.className || '',
        skills: parseJsonArray(profile.value.skills),
        interests: parseJsonArray(profile.value.interests),
        selfIntroduction: profile.value.selfIntroduction || ''
      }
    } else {
      console.warn('获取当前用户资料失败:', response.msg);
      ElMessage.error('获取个人资料失败: ' + (response.msg || '未知错误'));
      resetForm();
    }
  } catch (error) {
    console.error('加载当前用户资料失败:', error);
    ElMessage.error('网络错误，请稍后重试');
    resetForm();
  } finally {
    loading.value = false;
  }
}

// 加载统计数据
const loadStatistics = async () => {
  const validUserId = getValidUserId.value;
  console.log('开始加载统计数据，用户ID:', validUserId);
  
  // 检查用户ID是否有效
  if (!validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '') {
    console.warn('没有可用的用户ID来加载统计数据');
    ElMessage.warning('请先登录后再查看统计数据');
    return;
  }
  
  try {
    // 优先使用profile中的userId，然后是函数获取的有效用户ID
    const userIdToUse = profile.value.userId || validUserId;
    
    const response = await getStudentPortalData(userIdToUse);
    if (response.code === 200) {
      stats.value = {
        applicationCount: response.data.applicationCount || 0,
        appointmentCount: response.data.appointmentCount || 0,
        recommendationCount: response.data.recommendationCount || 0
      };
    } else {
      console.warn('获取统计数据失败:', response.msg);
      ElMessage.error('获取统计数据失败: ' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
}

const startEdit = () => {
  // 将当前profile数据复制到表单
  profileForm.value = {
    realName: profile.value.realName || '',
    studentNo: profile.value.studentNo || '',
    college: profile.value.college || '',
    major: profile.value.major || '',
    grade: profile.value.grade || '',
    className: profile.value.className || '',
    skills: parseJsonArray(profile.value.skills),
    interests: parseJsonArray(profile.value.interests),
    selfIntroduction: profile.value.selfIntroduction || ''
  }
  isEditing.value = true
}

const cancelEdit = () => {
  // 恢复到原始profile数据
  profileForm.value = {
    realName: profile.value.realName || '',
    studentNo: profile.value.studentNo || '',
    college: profile.value.college || '',
    major: profile.value.major || '',
    grade: profile.value.grade || '',
    className: profile.value.className || '',
    skills: parseJsonArray(profile.value.skills),
    interests: parseJsonArray(profile.value.interests),
    selfIntroduction: profile.value.selfIntroduction || ''
  }
  isEditing.value = false
}

const saveProfile = async () => {
  if (showInvalidUserWarning.value) {
    ElMessage.warning('用户信息不完整，请重新登录');
    return;
  }
  
  // 表单验证
  if (formRef.value) {
    try {
      await formRef.value.validate();
    } catch (error) {
      ElMessage.warning('请检查表单填写是否正确');
      return;
    }
  }
  
  // 获取有效的用户ID（从多来源）
  const userId = profile.value.userId || getValidUserId.value;
  
  if (!userId) {
    ElMessage.warning('无法获取有效的用户ID，请重新登录');
    return;
  }
  
  saving.value = true;
  try {
    // 准备提交的数据，将数组转换为JSON字符串，并确保包含userId
    const submitData = {
      ...profileForm.value,
      userId: userId, // 确保包含有效的userId
      skills: JSON.stringify(profileForm.value.skills),
      interests: JSON.stringify(profileForm.value.interests)
    };
    
    const response = await apiUpdateStudentProfile(submitData);
    if (response.code === 200) {
      ElMessage.success('个人资料更新成功');
      // 更新本地profile数据，保持与后端一致的格式
      profile.value = {
        ...profileForm.value,
        userId: submitData.userId,
        skills: submitData.skills,  // 使用JSON字符串格式
        interests: submitData.interests  // 使用JSON字符串格式
      };
      isEditing.value = false;
      // 重新加载以确保数据一致性
      loadProfile();
      loadStatistics();
    } else {
      ElMessage.error(response.msg || '更新失败');
    }
  } catch (error) {
    console.error('更新个人资料失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    saving.value = false;
  }
}

const refreshProfile = () => {
  loadProfile()
  loadStatistics()
  ElMessage.success('个人资料已刷新')
}

// 监听用户ID变化（props中的变化和localStorage中的变化）
watch(() => props.currentUserId, (newUserId) => {
  console.log('监听到props用户ID变化:', newUserId, typeof newUserId);
  // 无论props中的用户ID如何变化，都尝试重新加载数据
  // 因为getValidUserId计算属性会处理从localStorage获取
  loadProfile();
  loadStatistics();
})

// 额外监听localStorage中的userId变化（通过轮询实现）
let localStorageWatchTimer;
onMounted(() => {
  console.log('StudentProfile组件挂载，currentUserId:', props.currentUserId, typeof props.currentUserId);
  
  // 即使用户ID无效，也尝试加载当前用户资料
  Promise.all([
    loadProfile(),
    loadStatistics()
  ]).catch(err => {
    console.error('初始化数据加载失败:', err);
  });
  
  // 添加localStorage的轮询监听
  localStorageWatchTimer = setInterval(() => {
    const currentLocalStorageId = localStorage.getItem('userId');
    if (currentLocalStorageId && isUserIdInvalid.value) {
      // 如果localStorage中有用户ID但当前被认为无效，则重新加载
      console.log('检测到localStorage中的用户ID变化，重新加载数据');
      loadProfile();
      loadStatistics();
    }
  }, 3000); // 每3秒检查一次
})

// 清理定时器
onUnmounted(() => {
  if (localStorageWatchTimer) {
    clearInterval(localStorageWatchTimer);
  }
})

// Expose methods for parent component
defineExpose({
  loadProfile,
  refreshProfile
})
</script>

<style scoped>
.student-profile {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.profile-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-state {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.stats-card {
  background: #f8f9fa;
}

.stats-card .el-card__header {
  background: #f0f2f5;
}
</style>